package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.itheima.advice.LogOperation;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
//@Scope("prototype")//多列作用域
@Scope("singleton")//单列作用域spring默认的
/*
    作用域一共有五种
    单例有状态(有成员变量)的会出现线程安全问题
 */
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private EmpExprMapper empExprMapper;

    @Autowired
    private DeptService deptService;

    public EmpServiceImpl(){
        System.out.println("EmpServiceImpl被创建");
    }

    @Override
    public PageResult<Emp> selectEmp(EmpQueryParam empQueryParam) {
        Page<Emp> page = new Page<>(empQueryParam.getPage(),empQueryParam.getPageSize());
        LambdaQueryWrapper<Emp> wrapper = new LambdaQueryWrapper<>();
        if (empQueryParam.getName()!=null&&!"".equals(empQueryParam.getName())){
            wrapper.like(Emp::getName,empQueryParam.getName());
        }
        if (empQueryParam.getGender()!=null){
            wrapper.eq(Emp::getGender,empQueryParam.getGender());
        }
        if (empQueryParam.getBegin()!=null&&empQueryParam.getEnd()!=null){
            wrapper.between(Emp::getEntryDate,empQueryParam.getBegin(),empQueryParam.getEnd());
        }
        page = page(page,wrapper);
        page.getRecords().forEach(emp -> {
            Dept dept = deptService.getById(emp.getDeptId());
            if (dept != null){
                emp.setDeptName(dept.getName());
            }
        });
        PageResult<Emp> pageResult = new PageResult<>();
        pageResult.setTotal(page.getTotal());
        pageResult.setRows(page.getRecords());
        return pageResult;
    }


    @Transactional(rollbackFor = {Exception.class})
    @LogOperation
    public void savaEmp(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");

        empMapper.insert(emp);//使用MP自动返回id

        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)){
            exprList.forEach(s -> s.setEmpId(emp.getId()));
            empExprMapper.sava(exprList);
        }
    }

    @Transactional(rollbackFor = {Exception.class})
    @LogOperation
    public void deleteEmp(List<Integer> ids) {
        empMapper.deleteBatchIds(ids);

        empExprMapper.deleteExpr(ids);
    }


    @Transactional(rollbackFor = Exception.class)
    public Emp getEmpById(Integer id) {
        Emp emp = empMapper.selectById(id);

        List<EmpExpr> exprList = empExprMapper.getExprById(id);
        emp.setExprList(exprList);

        return emp;
    }
    @Transactional(rollbackFor = Exception.class)
    @LogOperation
    public void updateEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateById(emp);

        empExprMapper.deleteExpr(Arrays.asList(emp.getId()));

        if (!CollectionUtils.isEmpty(emp.getExprList())){
            emp.getExprList().forEach(empExpr -> empExpr.setEmpId(emp.getId()));
            empExprMapper.sava(emp.getExprList());
        }
    }
    public LoginInfo login(Emp emp) {
        LambdaQueryWrapper<Emp> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Emp::getUsername,emp.getUsername());
        lambdaQueryWrapper.eq(Emp::getPassword,emp.getPassword());
        Emp emp1 = empMapper.selectOne(lambdaQueryWrapper);
        LoginInfo loginInfo = new LoginInfo();
        if (emp1 != null){
            loginInfo.setId(emp1.getId());
            loginInfo.setUsername(emp1.getUsername());
            loginInfo.setName(emp1.getName());
            //使用JWT令牌生产token
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",emp1.getId());
            claims.put("username",emp1.getUsername());
            String token = JwtUtils.generateJwt(claims);
            loginInfo.setToken(token);
            return loginInfo;
        }
        return null;
    }
}
